package com.xfc.config.sms;

import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsSingleSenderResult;

import com.xfc.common.core.redis.RedisCache;
import com.xfc.config.Tools;
import com.xfc.wx.domain.ScSms;
import com.xfc.wx.service.IScSmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 *  短信发送工具类
 * @author lcj
 */
@Slf4j
@Component
public class SmsSend {

    @Autowired
    private IScSmsService smsService;
    @Autowired
    private RedisCache redisUtils;


    @Value("${sms.appId}")
    private Integer appId;
    /**秘钥**/
    @Value("${sms.SDKAppKey}")
    private String SDKAppKey;
    /**短信签名**/
    @Value("${sms.smsSign}")
    private String smsSign;


    /**
     *  短信发送
     * @param phone 手机号
     * @param templateId 模板id
     * @return
     */
    public boolean send(String phone,int templateId,String openId){
        //随机验证码
        int code= (int) ((Math.random()*9+1)*100000);
        //调用工具类
        SmsSingleSenderResult result=SmsUtils.sendCode(appId,SDKAppKey,smsSign,phone,"+86", String.valueOf(code),templateId);
        //json转换
        JSONObject resultObject = JSONObject.parseObject(String.valueOf(result));
        //获取状态
        String msg = resultObject.getString("errmsg");
        ScSms sms=new ScSms();
        sms.setCode(String.valueOf(code));
        sms.setCreateTime(new Date());
        sms.setType(1);
        sms.setMobile(phone);
        sms.setOpenId(openId);
        if("OK".equals(msg)){
            log.info("手机号："+phone+",验证码："+code+",发送成功");
            sms.setContent(String.valueOf(code));
            sms.setSend(1);
        }else {
            log.error("手机号："+phone+",验证码："+code+",发送失败");
            sms.setContent(String.valueOf(msg));
            sms.setSend(0);
        }
        try {
            //添加到数据库
            smsService.save(sms);
            //添加到redis
            redisUtils.setCacheObject(Tools.SMS_CODE+phone,code,5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }




}
